import 'package:flutter/material.dart';
import 'package:top_news/models/NewsResponse.dart';
import 'package:url_launcher/url_launcher.dart';

class NewListBuilder {
  static List<Widget> genWidgetsFromJson(NewsResponse newsResponse) {
    List<Widget> result = List();
    List<NewsItem> newItems = newsResponse.result.data.dataItems;
    for (int i = 0; i < newItems.length; i++) {
      result.add(getSingleItem(newItems[i]));
    }
    return result;
  }

  static Widget getSingleItem(NewsItem newsItem) {
    return Container(
      padding: EdgeInsets.all(5),
      child: InkWell(
        onTap: () {
          openDetail(newsItem.url);
        },
        child: Row(
          children: <Widget>[
            Image(
              alignment: Alignment.centerLeft,
              width: 100,
              height: 100,
              image: NetworkImage(newsItem.thumbnail_pic_s),
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(3.0),
                    child: Text(newsItem.date),
                    alignment: Alignment.topLeft,
                  ),
                  Container(
                    padding: EdgeInsets.all(3.0),
                    child: Text(
                      newsItem.title,
                      softWrap: false,
                      overflow: TextOverflow.ellipsis,
                    ),
                    alignment: Alignment.centerLeft,
                  ),
                  Container(
                    padding: EdgeInsets.all(3.0),
                    child: Text(newsItem.author_name),
                    alignment: Alignment.bottomLeft,
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  static void openDetail(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}
